package com.xtx.service.impl;

import com.xtx.entity.*;
import com.xtx.mapper.CategoryMapper;
import com.xtx.mapper.DetialMapper;
import com.xtx.mapper.SkuMapper;
import com.xtx.mapper.SpecsMapper;
import com.xtx.service.DetialService;
import com.xtx.vo.GoodsDetailVo;
import com.xtx.vo.SkuNameVo;
import com.xtx.vo.SpecsSkuVo;
import com.xtx.vo.SpecsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DetialServiceImpl implements DetialService {

    @Autowired
    private DetialMapper detialMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SpecsMapper specsMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Override
    public GoodsDetailVo getGoodsDetail(Integer id) {
        GoodsDetailVo goodsDetailVo = detialMapper.getGoodsDetail(id);
        Integer categoryId  = categoryMapper.getChildrenGoods(id);
        Integer goodsDetailId = goodsDetailVo.getId();
        List<Categories> categories = categoryMapper.getCategoriesById(categoryId);
        goodsDetailVo.setCategories(categories);
        goodsDetailVo.setDetailImages(detialMapper.getDetailImageById(goodsDetailVo.getId()));
        List<SpecsVo> specs = specsMapper.getSpecsById(goodsDetailId);
        specs.forEach(spec->{
            spec.setValues(specsMapper.getSpecsValuesById(spec.getId()));
        });
        goodsDetailVo.setSpecs(specs);
        goodsDetailVo.setSkus(getSku(goodsDetailId));
        return goodsDetailVo;
    }
    private List<SpecsSkuVo> getSku(Integer id){
        List<Sku> specsSkus = skuMapper.getSkuByGoodsId(id);
        List<SpecsSkuVo> specsSkuVos = new ArrayList<>();
        specsSkus.forEach(sku->{
            SpecsSkuVo specsSkuVo = new SpecsSkuVo();
            specsSkuVo.setId(sku.getId().toString());
            specsSkuVo.setSkuCode(sku.getSkuCode().toString());
            specsSkuVo.setPrice(sku.getPrice());
            specsSkuVo.setOldPrice(sku.getOldPrice());
            specsSkuVo.setInventory(sku.getInventory());
            specsSkuVo.setGoodsId(sku.getGoodsId());
            specsSkuVo.setSpecsId(sku.getSpecsId());
            for (int i = 0 ; i< sku.getSpecsId().length();i++){
                List<SkuNameVo> specs = specsMapper.getSpecsNameById(sku.getSpecsId());
                specs.forEach(specsName->{
                    specsName.setValueName(specsMapper.getSpecsValuesNameById(specsName.getId(),sku.getValueId1(),sku.getValueId2()));
                });
                specsSkuVo.setSpecs(specs);
            }
            specsSkuVos.add(specsSkuVo);
        });
        return specsSkuVos;
    }
}
